<template>
  <div class="mod-config">
 <el-form :inline="true" :model="dataForm" @keyup.enter.native="search()" >
        <el-form-item  >
        <span style="font-size: 24px; font-weight: bold;" >关注设备</span>
      </el-form-item>
    <div></div>

<!-- <el-row>
  <el-col :span="5">
    
<el-table :data="dataList" border v-loading="dataListLoading" @selection-change="selectionChangeHandle" style="width: 120%; height: 900px; " >
      
      <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
      <el-table-column type="index"  header-align="center" align="center" label="序号"></el-table-column>
      <el-table-column prop="deviceId" header-align="center" align="center"  label="设备编号"></el-table-column>
      <el-table-column prop="deviceName" header-align="center" align="center" label="设备名称"  width="50"></el-table-column>
      
      <el-table-column fixed="right" header-align="center" align="center" width="50" label="操作">
        <template slot-scope="scope">
          <el-button  type="text" size="small" @click="deleteHandle(scope.row.id,scope.row.deviceId)">查看</el-button>
          <el-button v-if="isAuth('dss:follow:delete')" type="text" size="small" @click="deleteHandle(scope.row.id,scope.row.deviceId)">取消关注</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination  @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex" :page-sizes="[10, 20, 50, 100]" :page-size="pageSize"
    :total="totalCount" layout="total,sizes,prev,pager,next,jumper"></el-pagination>
  </el-col>
  <el-col :span="19">
    <el-form-item  >
        <span style="font-size: 24px; font-weight: bold;" >关注设备</span>
      </el-form-item>
  </el-col>
</el-row> -->
    <el-tabs tab-position="left" style="height: 650px; width: 100%;" type="border-card"   v-model="chars"  @tab-click="tab()" :before-leave="tab()" >
      <el-tab-pane  name="a" disabled> 
    <span  slot="label" style="font-size: 20px;  color: #110;" >
      <el-row>
        <el-col :span="3">
      <i class="el-icon-setting"></i></el-col><el-col :span="2">设备名称</el-col> 
      <el-button v-if="isAuth('dss:follow:save')" type="primary" size="small" @click="addOrUpdateHandle()" icon="el-icon-star-on">新增关注</el-button>
    </el-row></span >
  </el-tab-pane >

  <el-tab-pane  name="b" disabled>
    <span slot="label" style="font-size: 20px;  color: #110; line-height: 10px" :hit="true">
      <el-row>
        <el-col :span="24">
    <el-input v-model="dataForm.deviceName" placeholder="请输入设备名称"  clearable class="input-with-select1" >
    <el-button slot="append" icon="el-icon-search"  class="green-button" @click="search()"></el-button>
       </el-input>
      </el-col>
    </el-row>
      </span >
  </el-tab-pane>
  
    <el-tab-pane  v-for="(device,index) in this.dataList" :label="device.deviceName" :key="device.followId"  :value="device"  :name="device.followId">      
      <span slot="label" style="font-size: 16px;  color: #110; line-height: 35px; " >
        <el-row style="height: 30px; ">
     <el-col :span="4">
     <el-tag type="info" style="font-size: 15px; color: #110;" size="mini" color="FFFFFF">  {{ index+1 }}  </el-tag>
    </el-col>
     <el-col :span="6">
      {{ device.deviceName }}
      </el-col>     
      <el-col :span="14">
        <el-button v-if="isAuth('dss:follow:delete')" style="  color: red; " type="text" icon="el-icon-delete"  @click="deleteHandle(device.followId,device.deviceId)" ></el-button>
      </el-col>
    </el-row>
      </span >
    <el-row style="height: 30px; ">
          <el-col :span="6">
      <el-form :inline="true" :model="device" @keyup.enter.native="search()" >
        <el-form label-position="left" inline class="demo-table">
          <el-form-item label="车间名称">
            <span>{{ device.workshopName }}</span>
          </el-form-item>
          <el-form-item label="设备类型">
            <span>{{ device.name }}</span>
          </el-form-item>
          <el-form-item label="设备编号">
            <span>{{ device.deviceId}}</span>
          </el-form-item>
          <el-form-item label="设备名称">
            <span>{{ device.deviceName }}</span>
          </el-form-item>
          <el-form-item label="设备型号">
            <span>{{ device.deviceModel }}</span>
          </el-form-item>
       
          <el-form-item label="生产日期">
            <span>{{ device.produceTime }}</span>
          </el-form-item>
          <el-form-item label="开始使用日期">
            <span>{{ device.startUseTime}}</span>
          </el-form-item>
          <el-form-item label="维保到期">
            <span>{{ device.maintenanceTime }}</span>
          </el-form-item>
          <el-form-item label="制造厂">
            <span>{{ device.factory }}</span>
          </el-form-item>
          <el-form-item label="传感器ID">
            <span>{{ device.sensorId }}</span>
          </el-form-item>
          <el-form-item label="备注">
            <span>{{ device.notes}}</span>
            
          </el-form-item> 
        
        </el-form>
    </el-form> 
  </el-col>
    <el-col :span="18" >
      <el-row>
        <el-col :span="12" >
      <div  :id="`bar-${device.id}`" style="width: 100%;height:300px;"></div>
        </el-col>
        <el-col :span="12" >
     <div :id="`pie-${device.id}`" style="width: 100%;height:300px;"></div>
        </el-col>
     </el-row>
  <div :id="`line-${device.id}`" style="width: 100%;height:300px;"></div>
      
   
    
  </el-col>
</el-row>
    </el-tab-pane>
    
            
        
 
  </el-tabs>
  <el-col :span="1">
  <el-pagination :pager-count="7"  background @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex" :page-sizes="[10, 20, 50, 100]" :page-size="pageSize"
  :total="totalCount" layout="total,prev,pager,next,jumper"></el-pagination>
  </el-col>
 </el-form>
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
  </div>
  
</template>


<style >




  .demo-table {
    font-size: 0;
  }
  .demo-table label {
    width: 100px;
    color: #0b5dce;
  }
  .demo-table .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 90%;
  }
</style>

<script>

// import { method } from 'lodash';
// import AddOrUpdate from './repairMange-add-or-update.vue'
// import Vue from 'vue';
// import ElementUI from 'element-ui';
// import 'element-ui/lib/theme-chalk/index.css'; 

import AddOrUpdate from './follow-add'
import * as echarts from 'echarts'
  export default{
    computed: {//计算属性根据依赖关系进行缓存的计算
    // 按设备ID分组
    productionGroupedList() {
      const groups = {}
      this.productionList.forEach(item => {
        if (!groups[item.deviceId]) {
          groups[item.deviceId] = { deviceId: item.deviceId, outputs: [] }
        }
        groups[item.deviceId].outputs.push({ date: item.date, value: item.production})
      })
      return Object.values(groups)
    },
    efficiencyGroupedList() {
      const groups = {}
      this.efficiencyList.forEach(item => {
        if (!groups[item.deviceId]) {
          groups[item.deviceId] = { deviceId: item.deviceId, outputs: [] }
        }
        groups[item.deviceId].outputs.push({ date: item.date, value: item.efficiency})
      })
      return Object.values(groups)
    }
  },
    data(){
      return {
        chars:'0',
        efficiencyList:[],
        productionList:[],
        dataForm:{
          deviceName:''
        },
        dataList:[],
        pageIndex:1,
          pageSize:14,
        totalCount:0,
        dataListLoading:false,
        dataListSelections:[],
         addOrUpdateVisible:false,
 

      }
    },
    components:{
      AddOrUpdate
    },


    activated(){
      this.getDataList()
  
    },

    methods:{
      tab(){
        this.getCharts()
      },

      getCharts() {
        this. productionGroupedList.forEach(device =>{
         
          
   // 获取当前日期
   const currentDate=new Date()
    // 生成近7天的日期数组
    const last7Days=[]
    for (let i=0;i<7;i++) {
      const date = new Date(currentDate);
      date.setDate(date.getDate()-i)//获取过去第i天的日期
      last7Days.push(date.toISOString().split('T')[0]) //格式化为yyyy-mm-dd
    }
    // 只显示近7天的数据
    const last7DaysData=device.outputs.filter(d=>{
      const dataDate=d.date.split(' ')[0] // 获取日期部分
      return last7Days.includes(dataDate) // 检查该日期是否在近7天内
    })
    // 获取近7天的日期和对应的产量数据
    const dates=last7Days.reverse() //反转数组,使得日期按顺序显示
    const values =dates.map(date => {
      // 根据日期获取对应的产量数据
      const matchingData=last7DaysData.find(d => d.date.split(' ')[0] === date)
      return matchingData?matchingData.value:0; // 如果没有数据，默认产量为0
    })

        const chartDom=document.getElementById(`bar-${device.deviceId}`)
           if (!chartDom) return;
           console.log(device);
           const chartBar=echarts.init(chartDom)
           chartBar.setOption({
             title: {
               text:'设备近7天产量'
             },
             tooltip: {},
             xAxis: {
               data: dates,
               name: '日期',
               axisLabel: {
                 formatter: function (value) {
                   // 格式化日期，显示月和日
                   const date=new Date(value)
                   const month=date.getMonth()+1 // 获取月0-11，所以加1
                   const day=date.getDate() // 获取日
                   return `${month}-${day}` // 显示格式为 月-日
                 }
               }
             },
             yAxis: {
               name: '产量/件'
             },
             series: [
               {
                 name: '产量/件',
                 type: 'bar',
                 data: values,
               }
             ]
           });
    const chartDomLine = document.getElementById(`line-${device.deviceId}`);
    if (!chartDomLine) return;
    const chartLine=echarts.init(chartDomLine);
    chartLine.setOption({
      title: {
        text:'设备产量趋势'
      },
      tooltip: {
        trigger: 'axis', 
      },
      xAxis: {
        data:device.outputs.map(d => d.date.split(' ')[0]),
        name: '日期'
      },
      yAxis: {
        name: '产量/件'
      },
      series: [
        {
          name: '产量/件',
          type: 'line', 
          data: device.outputs.map(d => d.value),
          smooth: false, //平滑的折线
          lineStyle: {
            color: 'red'
          },
        }
      ]
    });
    chartLine.resize({
  width: 800,
});
        chartBar.resize({
  width: 400,
});
})
      this. efficiencyGroupedList.forEach(device =>{
   // 获取当前日期
   const currentDate=new Date()
    // 生成近30天的日期数组
    const last30Days=[]
    for (let i=0;i<30;i++) {
      const date = new Date(currentDate);
      date.setDate(date.getDate()-i); //获取过去第i天的日期
      last30Days.push(date.toISOString().split('T')[0]) //格式化为yyyy-mm-dd
    }
    // 只显示近30天的数据
    const last30DaysData=device.outputs.filter(d=>{
      const dataDate=d.date.split(' ')[0]// 获取日期部分
      return last30Days.includes(dataDate) // 检查该日期是否在近30天内
    })
    // 获取近30天的日期和对应的产量数据
    const dates=last30Days.reverse(); //反转数组,使得日期按顺序显示
    const values =dates.map(date => {
      // 根据日期获取对应的使用率
      const matchingData=last30DaysData.find(d => d.date.split(' ')[0] === date)
      return matchingData?matchingData.value:0
    })
        // const count = values.length;
    // const count = values.length;
    const count = last30DaysData.length;
    console.log(count );
    
    // 计算总值
    const sum = values.reduce((acc, curr) => acc + curr, 0);//acc 是累加器，curr 是当前值，0 是初始值
    const chartDomPie = document.getElementById(`pie-${device.deviceId}`)
    if (!chartDomPie) return;
    const chartPie=echarts.init(chartDomPie)
      chartPie.setOption({
        title: {
    text: '设备近30天总使用效率',
    left: 'center'
  },
  tooltip: {
    trigger: 'item',
    formatter: '{b}: {d}%' // {b}是名称，{d}是百分比
  },
  legend: {
    orient: 'vertical',
    left: 'left'
  },
  series: [
    {
         radius: '60%',
      type: 'pie',
      stillShowZeroSum: false,
      data: [ {
          value: count-sum,
          name: '待机率'
        },
        {
          value: sum,
          name: '使用效率'
        },
       
      ]
    }
  ]
});
chartPie.resize({
  width: 400,
});
      })

    },
      search() { 
        this.pageIndex=1
        this.getDataList()
        console.log(this.groupedList);
        
      },
      getDataList(){
        this.dataListLoading=true
        this.$http({
          url:this.$http.adornUrl('/dss/follow/list'),
          method:'get',
          params:this.$http.adornParams({
            'page':this.pageIndex,
            'limit':this.pageSize,
            'deviceName':this.dataForm.deviceName
          })
        }).then(({data})=>{
          if (data && data.code===0){
            this.dataList=data.page.list
            this.totalCount=data.page.totalCount
            this.productionList=data.production
            this.efficiencyList=data.efficiency
      
            
          }else{
            this.dataList=[]
            this.totalCount=0
          }
          this.dataListLoading=false
        })
      },
      sortChange(column){
          this.isAsc=column.order=="ascending"?'asc':'desc'
     
        this.getDataList()
      },
      sizeChangeHandle(val){
        this.pageSize=val
        this.pageIndex=1
        this.getDataList()
      },
      currentChangeHandle(val){
        this.pageIndex=val
        this.getDataList()
      },
      selectionChangeHandle(val){
        this.dataListSelections=val
      },
      addOrUpdateHandle(){
        this.addOrUpdateVisible=true
        this.$nextTick(()=>{
          this.$refs.addOrUpdate.init(this.dataList)
        })
      },
      deleteHandle(id,deviceId){
       
        var deviceIds=deviceId?[deviceId]:this.dataListSelections.map(item=>{
          return item.deviceId
        })
        var ids=id?[id]:this.dataListSelections.map(item=>{
          return item.id
        }) 
        console.log(this.dataList)
        this.$confirm(`确定对[设备编号为${deviceIds.join(',')}]的设备进行[${deviceId?'取消关注':'批量取关'}]操作?`,'提示', {
          confirmButtonText:'确定',
           cancelButtonText:'取消',
          type:'warning'
        }).then(()=>{
          this.$http({
            url:this.$http.adornUrl('/dss/follow/delete'),
            method:'post',
            data:this.$http.adornData(ids,false)
          }).then(({data})=>{
            if (data && data.code===0){
              this.$message({
                 message:'操作成功',
                type:'success',
                duration:800, 
                 onClose:()=>{
                  this.getDataList()
                }
              })
            }else{
              this.$message.error(data.msg)
            }
          })
        }).catch(()=>{})
      }
    }
  }
</script>
